package com.spark.gaea.config.service.easyzk;

import com.google.common.base.Charsets;
import com.google.common.base.MoreObjects;
import com.google.common.base.Preconditions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.util.Map;
import java.util.Properties;

public class ConfigLocalCache {
	private String localCachePath;
	private static final String SUFFIX = ".cache";
	private static final Logger LOGGER = LoggerFactory.getLogger(ConfigLocalCache.class);

	public ConfigLocalCache() {
		this("/config-service");
	}

	public ConfigLocalCache(final String localCachePath) {
		this.localCachePath = localCachePath;
	}

	public void saveLocalCache(final ConfigNode configNode, final String node) {
		final String localFilePath = this.genCacheFilePath(node);
		if (ConfigLocalCache.LOGGER.isDebugEnabled()) {
			ConfigLocalCache.LOGGER.debug(String.format("Saving cache to file: [%s]", localFilePath));
		}
		final Map<String, String> data = configNode.exportProperties();
		if (data != null && data.size() > 0) {
			final Properties properties = new Properties();
			for (final Map.Entry<String, String> entry : data.entrySet()) {
				properties.put(entry.getKey(), entry.getValue());
			}
			Writer writer = null;
			try {
				writer = new OutputStreamWriter(new FileOutputStream(localFilePath), Charsets.UTF_8);
				properties.store(writer, String.format("Local cache of configs group: %s", node));
			} catch (IOException e) {
				ConfigLocalCache.LOGGER.error(e.getMessage(), e);
			} finally {
				if (writer != null) {
					try {
						writer.close();
					} catch (IOException ex) {}
				}
			}
		}
	}

	private String genCacheFilePath(final String node) {
		this.checkFolderExistence();
		return this.localCachePath + File.separatorChar + node + ".cache";
	}

	private void checkFolderExistence() {
		final File file = new File(this.localCachePath);
		if (!file.exists()) {
			Preconditions.checkState(file.mkdirs());
		}
	}

	@Override
	public String toString() {
		return MoreObjects.toStringHelper(this).add("localCachePath", this.localCachePath).toString();
	}

}
